#include <functional>
#include <iostream>
#include <memory>

using namespace std;

class Base {
 private:
  int _data;

 public:
  Base() = default;
  Base(int data) : _data(data) {}
  ~Base() { cout << "Base::~Base()" << endl; };
};

class Inherit : public Base {
 private:
  int _exData;

 public:
  Inherit() = default;
  Inherit(int data, int exdata) : Base(data), _exData(exdata) {}
  ~Inherit() { cout << "Inherit::~Inherit()" << endl; };
};

template <typename T>  // Base
class _shared_ptr {
 private:
  T *_data = nullptr;
  // 保存子类类型信息（析构函数）
  function<void()> _delete = nullptr;

 public:
  // Inherit
  template <typename T2>
  _shared_ptr(T2 *ptr) : _data(ptr), _delete([ptr]() { delete ptr; }) {}
  ~_shared_ptr() { _delete(); }
  T *operator->() { return _data; }
};

int main(int argc, char const *argv[]) {
  // 1. 手动new/delete
  // Base *a = new Inherit(1, 2);
  // delete a; // ~Base非虚情况下不调用

  // 2. std::shared_ptr
  shared_ptr<Base> a(new Inherit(1, 2));  // ~Base & ~Inherit

  // 3. 模拟shared_ptr
  _shared_ptr<Base> b(new Inherit(1, 2));  // ~Base & ~Inherit
  return 0;
}
